package servlet;

import dao.Messagedao;
import dao.Privatedao;
import service.Privateservice;
import service.Userservice;
import vo.Message;
import vo.Private;
import vo.ResultInfo;
import vo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;
@WebServlet("/PrivateServlet")
public class PrivateServlet extends HttpServlet {
    private Privatedao privatedao = new Privatedao();
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session= request.getSession();
        User user= (User) session.getAttribute("user");
        String username= user.getUsername();
        String privatename=request.getParameter("object");
        String text = request.getParameter("text");
        Date time = new Date();
        Privateservice privateservice =new Privateservice();
        ResultInfo<User> resultInfo = null;
        try {
            resultInfo = privateservice.check(privatename);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        if(resultInfo.getCode()==0){
            request.setAttribute("error_which", resultInfo.getWhich());
            request.getRequestDispatcher("private.jsp").forward(request,response);
        }
        else {
            Private pri=new Private();
            pri.setUsername(username);
            pri.setPrivatename(privatename);
            pri.setMessage(text);
            pri.setTime(time);
            try {
                privatedao.addMessage(pri);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

        try {
            session.setAttribute("privates", privatedao.getMessages(username));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        try {
            session.setAttribute("owners", privatedao.getOwnmessages(username));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        request.getRequestDispatcher("/private.jsp").forward(request, response);

    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
